//
//  QNCommonTool.m
//  QNReuseTool
//
//  Created by rsh on 2019/10/15.
//  Copyright © 2019年 rsh. All rights reserved.
//

#import "QNCommonTool.h"
#import "ZZACMacros.h"
#import "QNMBPLoadView.h"
#import "QNNetDefine.h"

#define QNReuseToolPodName @"QNReuseTool"

@implementation QNCommonTool


+ (void)loadingWithText:(NSString *)text andInView:(UIView *)view{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    hud.mode = MBProgressHUDModeCustomView;
    hud.label.text = text;
    hud.minSize = CGSizeMake(77, 77);
    hud.contentColor = UIColorFromRGB(0xdbdbdb);
    hud.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
    hud.bezelView.color = [UIColor blackColor];
    hud.bezelView.alpha = 0.75;
    hud.label.textColor = UIColorFromRGB(0xdbdbdb);
    hud.label.font = [UIFont systemFontOfSize:14];
    hud.margin = 10;
    hud.customView = [self contentView];
    
}
+ (void)hideLoadingView:(UIView *)view{
    [MBProgressHUD hideHUDForView:view animated:YES];
}

+(UIView *)contentView{
    
    QNMBPLoadView *vv = [[QNMBPLoadView alloc]init];
    
    UIImageView *wheelView = [[UIImageView alloc] initWithImage:[[UIImage wg_imgWithName:@"Bicycle-wheel" bundle:QNReuseToolPodName targetClass:self.class] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    
    UIImageView *loadingView = [[UIImageView alloc] initWithImage:[[UIImage wg_imgWithName:@"bicycle_loading" bundle:QNReuseToolPodName targetClass:self.class] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    
    [vv addSubview:loadingView];
    [vv addSubview:wheelView];
    CGFloat x = (loadingView.image.size.width - wheelView.image.size.width)/2.0;
    CGFloat y = (loadingView.image.size.height - wheelView.image.size.height)/2.0;
    loadingView.frame = CGRectMake(0, 0, loadingView.image.size.width, loadingView.image.size.height);
    wheelView.frame = CGRectMake(x, y, wheelView.image.size.width, wheelView.image.size.height);
    
    CABasicAnimation *animation =  [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    animation.fromValue = @(0);
    animation.toValue =  @(M_PI * 2);
    animation.duration  = 0.85;
    animation.fillMode =kCAFillModeForwards;
    animation.repeatCount = MAXFLOAT;
    animation.removedOnCompletion = NO;
    [loadingView.layer addAnimation:animation forKey:nil];
    
    return vv;
}



/**
 *
 *
 *  判断用户输入的密码是否符合规范，符合规范的密码要求：
 1. 长度大于8位
 2. 密码中必须同时包含数字和字母
 写出来的正则表达式为：
 ^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$
 分开来注释一下：
 ^ 匹配一行的开头位置
 (?![0-9]+$) 预测该位置后面不全是数字
 (?![a-zA-Z]+$) 预测该位置后面不全是字母
 [0-9A-Za-z] {8,16} 由8-16位数字或这字母组成
 $ 匹配行结尾位置
 注：(?!xxxx) 是正则表达式的负向零宽断言一种形式，标识预该位置后不是xxxx字符。
 */

+(BOOL)judgePassWordLegal:(NSString *)pass
{
    BOOL result = false;
    if ([pass length] >= 8){
        // 判断长度大于8位后再接着判断是否同时包含数字和字符
        NSString * regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$";
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
        result = [pred evaluateWithObject:pass];
    }
    return result;
}


//设置label行与行的间距
+(void)setLineSpaceWithLabel:(UILabel *)lb withSpace:(CGFloat)space
{
    if(lb.text.length != 0)
    {
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:lb.text];
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        [paragraphStyle setLineSpacing:space];
        [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [lb.text length])];
        //         [attributedString addAttribute:NSFontAttributeName value:lb.font range:NSMakeRange(0, [lb.text length])];
        lb.attributedText = attributedString;
    }
}


// 字典转json字符串方法
+(NSString *)dictionaryConvertToJsonData:(NSDictionary *)dict
{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    if (!jsonData) {
        GCLog(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    
    NSRange range2 = {0,mutStr.length};
    //去掉字符串中的换行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    return mutStr;
}


//字典转json字符串方法，不去掉里面的换行符
+(NSString *)dictionaryToJsonStr:(NSDictionary *)dict
{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    if (!jsonData) {
        GCLog(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    return jsonString;
}


//将字符串转成字典
+(NSDictionary *)parseJSONStringToNSDictionary:(NSString *)JSONString
{
    if (JSONString == nil || [JSONString isKindOfClass:[NSNull class]]) {
        return nil;
    }else{
        NSData *JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
        NSError *err;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:&err];
        if(err){
            GCLog(@"json解析失败：%@",err);
            return nil;
        }
        return dic;
    }
}


//设置颜色渐变并返回一个layer
+(CAGradientLayer *)colorLayer:(NSArray *)colors withLocations:(NSArray *)locations withStartPoint:(CGPoint)sPoint withEndPoint:(CGPoint)ePoint withSize:(CGSize)size
{
    CAGradientLayer *colorLayer = [CAGradientLayer layer];
    colorLayer.frame = CGRectMake(0, 0, size.width, size.height);
    colorLayer.colors = colors;// 颜色分配
    colorLayer.locations = locations;// 颜色分割线
    colorLayer.startPoint = sPoint;
    colorLayer.endPoint = ePoint;//决定方向的向量的两点
    return colorLayer;
}


+(void)addGradient:(CGRect)frame view:(UIView *)view fcolor:(UIColor *)fcolor scolor:(UIColor *)scolor
{
    //背景色渐变
    CAGradientLayer *gl = [CAGradientLayer layer];
    gl.frame = frame;
    gl.startPoint = CGPointMake(0, 0);
    gl.endPoint = CGPointMake(1, 1);
    gl.colors = @[(__bridge id)fcolor.CGColor,(__bridge id)scolor.CGColor];
    gl.locations = @[@(0.0),@(1.0f)];
    [view.layer insertSublayer:gl above:0];
}

/** 取消searchBar背景色 */
+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size
{
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

//将11位电话号码13533441234 转换成 135***1234
+(NSString *)transPhoneNumWithString:(NSString *)str
{
    NSMutableString *str1 = [[NSMutableString alloc]init];
    if (str.length==11) {
        NSRange rang = NSMakeRange(3, 4);
        [str1 setString:str];
        [str1 replaceCharactersInRange:rang withString:@"****"];
    }
    NSString *string = [NSString stringWithFormat:@"%@",str1];
    return string;
}

//将18位或者15位身份证号  转换成 4414***234X
+(NSString *)transIdNumWithString:(NSString *)str
{
    NSMutableString *str1 = [[NSMutableString alloc]init];
    if (str.length == 18) {
        NSRange rang = NSMakeRange(4, 10);
        [str1 setString:str];
        [str1 replaceCharactersInRange:rang withString:@"****"];
    }else if (str.length == 15){
        NSRange rang = NSMakeRange(4, 7);
        [str1 setString:str];
        [str1 replaceCharactersInRange:rang withString:@"****"];
    }
    NSString *string = [NSString stringWithFormat:@"%@",str1];
    return string;
}


//解析JSON获取字典
+(NSDictionary *)getDictionaryWithJSONStr:(NSString *)jsonStr
{
    if (jsonStr == nil || [jsonStr isKindOfClass:[NSNull class]]) {
        return nil;
    }else{
        NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
        NSError *err;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&err];
        if(err) {
            NSLog(@"json解析失败：%@",err);
            return nil;
        }
        return dic;
    }
}

//解析JSON获取数组
+(NSArray *)getArrayWithJSONStr:(NSString *)jsonStr
{
    if (jsonStr == nil || [jsonStr isKindOfClass:[NSNull class]]){
        return nil;
    }else{
        NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
        NSError *err;
        NSArray *ary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&err];
        if(err) {
            NSLog(@"json解析失败：%@",err);
            return nil;
        }
        return ary;
    }
}


//根据省份证号获取年龄
+(NSString *)getIdentityCardAge:(NSString *)numberStr
{
    
    NSDateFormatter *formatterTow = [[NSDateFormatter alloc]init];
    [formatterTow setDateFormat:@"yyyy-MM-dd"];
    NSDate *bsyDate = [formatterTow dateFromString:numberStr];
    
    NSTimeInterval dateDiff = [bsyDate timeIntervalSinceNow];
    
    int age = trunc(dateDiff/(60*60*24))/365;
    
    return [NSString stringWithFormat:@"%d",-age];
    
}


//图片转字符串
+(NSString *)UIImageToBase64Str:(UIImage *) image
{
    NSData *data = UIImageJPEGRepresentation(image, 1.0f);
    NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    return encodedImageStr;
}


//字符串转图片
+(UIImage *)Base64StrToUIImage:(NSString *)encodedImageStr
{
    if (!encodedImageStr.length) return nil;
    NSData *decodedImageData = [[NSData alloc] initWithBase64EncodedString:encodedImageStr options:NSDataBase64DecodingIgnoreUnknownCharacters];
    UIImage *decodedImage = [UIImage imageWithData:decodedImageData];
    return decodedImage;
}


/**
 *
 *图片的压缩处理2步曲
 1）宽高均大于1280，取较大值等于1280，较大值等比例压缩
 2）宽或高一个大于1280，取较大的等于1280，较小的等比压缩
 3）宽高均小于1280，压缩比例不变
 *
 1）图片大于1M的，将压缩系数调整到0.7
 2）图片在0.5M<image<1M,将压缩系数调整到0.8
 3）图片小雨0.5M，压缩系数可以写0.9或者1
 **/
+(NSData *)zipNSDataWithImage:(UIImage *)sourceImage
{
    //进行图像尺寸的压缩
    CGSize imageSize = sourceImage.size;//取出要压缩的image尺寸
    CGFloat width = imageSize.width;    //图片宽度
    CGFloat height = imageSize.height;  //图片高度
    //1.宽高大于1280(宽高比不按照2来算，按照1来算)
    if (width>1280) {
        if (width>height) {
            CGFloat scale = width/height;
            height = 1280;
            width = height*scale;
        }else{
            CGFloat scale = height/width;
            width = 1280;
            height = width*scale;
        }
        //2.高度大于1280
    }else if(height>1280){
        CGFloat scale = height/width;
        width = 1280;
        height = width*scale;
    }else{
    }
    UIGraphicsBeginImageContext(CGSizeMake(width, height));
    [sourceImage drawInRect:CGRectMake(0,0,width,height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    //进行图像的画面质量压缩
    NSData *data=UIImageJPEGRepresentation(newImage, 1.0);
    if (data.length>100*1024) {
        if (data.length>1024*1024) {//1M以及以上
            data=UIImageJPEGRepresentation(newImage, 0.7);
        }else if (data.length>512*1024) {//0.5M-1M
            data=UIImageJPEGRepresentation(newImage, 0.8);
        }else if (data.length>200*1024) {
            //0.25M-0.5M
            data=UIImageJPEGRepresentation(newImage, 0.9);
        }
    }
    return data;
}

//  颜色转换为背景图片
+ (UIImage *)imageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}


//加入购物车动画
+(void)animationWithView:(UIView *)view startCenter:(CGPoint)start finishCenter:(CGPoint)finish
{
    
    CAKeyframeAnimation *keyframeAnimation=[CAKeyframeAnimation animationWithKeyPath:@"position"];
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, start.x, start.y);//移动到起始点
    CGPathAddQuadCurveToPoint(path, NULL, finish.x, start.y, finish.x, finish.y);
    keyframeAnimation.path = path;
    CGPathRelease(path);
    
    //    NSLog(@"两个点坐标1----%@ \n  2-----%@  \n   3------%@",NSStringFromCGPoint(start),NSStringFromCGPoint(CGPointMake(finish.x, start.y)),NSStringFromCGPoint(finish));
    
    //缩放动画
    CABasicAnimation *anima2 = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    anima2.fromValue = [NSNumber numberWithFloat:1.0f];
    anima2.byValue = [NSNumber numberWithFloat:2.0f];
    anima2.toValue = [NSNumber numberWithFloat:1.0f];
    
    //旋转动画
    CABasicAnimation *anima3 = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    anima3.toValue = [NSNumber numberWithFloat:M_PI*8];
    //组动画
    CAAnimationGroup *groupAnimation = [CAAnimationGroup animation];
    groupAnimation.animations = [NSArray arrayWithObjects:keyframeAnimation,anima2,anima3, nil];
    groupAnimation.duration = 1.0f;
    [view.layer addAnimation:groupAnimation forKey:@"groupAnimation"];
}


//跑马灯动画
+(void)addMarqueeAnimationWithView:(UIView *)view
{
    
    UIView *animationView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 10)];
    animationView.backgroundColor = [UIColor  yellowColor];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 10, 10)];
    label.text = @">>";
    label.textAlignment = NSTextAlignmentCenter;
    [animationView addSubview:label];
    
    [view addSubview:animationView];
    //创建动画对象
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    
    //设置value
    NSValue *value1=[NSValue valueWithCGPoint:CGPointMake(0, 0)];
    NSValue *value2=[NSValue valueWithCGPoint:CGPointMake(view.frame.size.width - 0, 0)];
    NSValue *value3=[NSValue valueWithCGPoint:CGPointMake(view.frame.size.width , view.frame.size.height )];
    NSValue *value4=[NSValue valueWithCGPoint:CGPointMake(0, view.frame.size.height )];
    NSValue *value5=[NSValue valueWithCGPoint:CGPointMake(0, 0)];
    
    animation.values=@[value1,value2,value3,value4,value5];
    
    //重复次数 默认为1
    animation.repeatCount=MAXFLOAT;
    
    //设置是否原路返回默认为不
    //    animation.autoreverses = YES;
    
    //设置移动速度，越小越快
    animation.duration = 5.0f;
    
    animation.removedOnCompletion = NO;
    
    animation.fillMode = kCAFillModeForwards;
    
    animation.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    //    NSLog(@"keyTimes---%@",animation.values);
    //给这个view加上动画效果
    [animationView.layer addAnimation:animation forKey:nil];
    
    
    [UIView animateWithDuration:5/4 animations:^{
        [UIView setAnimationRepeatCount:MAXFLOAT];
        //旋转动画
        CABasicAnimation *animation2 = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
        animation2.toValue = [NSNumber numberWithFloat:M_PI/2];
        [animationView.layer addAnimation:animation2 forKey:@"a"];
    } completion:^(BOOL finished) {
        
    }];
    
    
    //
    //    //组动画
    //    CAAnimationGroup *groupAnimation = [CAAnimationGroup animation];
    //    groupAnimation.animations = [NSArray arrayWithObjects:animation,animation2, nil];
    //    groupAnimation.duration = 5.0f;
    //    [animationView.layer addAnimation:groupAnimation forKey:@"groupAnimation"];
    
}

//计算字符串宽高
+ (CGSize)sizeWithFont:(UIFont*)font Str:(NSString*)str withMaxWidth:(CGFloat)maxWidth
{
    NSDictionary *attribute = @{NSFontAttributeName: font};
    CGSize strSize = [str boundingRectWithSize:CGSizeMake(maxWidth, CGFLOAT_MAX) options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading) attributes:attribute context:nil].size;
    
    return strSize;
}

//URL字符串的URLencode
+(NSString*)encodeString:(NSString*)unencodedString
{
    
    // CharactersToBeEscaped = @":/?&=;+!@#$()~',*";
    // CharactersToLeaveUnescaped = @"[].";
    
    NSString *encodedString = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)unencodedString,
                                                              NULL,
                                                              (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                              kCFStringEncodingUTF8));
    
    return encodedString;
}

//URLDEcode
+(NSString *)decodeString:(NSString*)encodedString
{
    //NSString *decodedString = [encodedString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding ];
    
    NSString *decodedString  = (__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,
                                                                                                                     (__bridge CFStringRef)encodedString,
                                                                                                                     CFSTR(""),
                                                                                                                     CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    return decodedString;
}



//iOS设备是否越狱的判断代码
+(BOOL)isJailBreak
{
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"cydia://"]]) {
        GCLog(@"The device is jail broken!");
        return YES;
    }
    GCLog(@"The device is NOT jail broken!");
    return NO;
}




@end
